package com.cheng.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.cheng.bos.actionUtils.ActionUtils;
import com.cheng.bos.pinyin4jUtils.pinyin4jUtils;
import com.cheng.domain.base.Area;
import com.cheng.service.base.AreaService;
import com.opensymphony.xwork2.ActionContext;

@Controller
@Scope("prototype")
@Namespace("/area")
@ParentPackage("json-default")
public class AreaAction extends ActionUtils<Area>{
	@Autowired
	private AreaService areaService;
	
	//封装id页面传递id
	private String ids;
	
	public void setIds(String ids) {
		this.ids = ids;
	}

	//删除区域
	@Action(value="delarea", results={@Result(name="success",location="../pages/base/area.html",type="redirect")})
	public String delArea(){
		String[] str =ids.split(",");
		areaService.delArea(str);
		return SUCCESS;
	}
	
	//添加区域
	@Action(value="addrea", results={@Result(name="success",location="../pages/base/area.html",type="redirect")})
	public String addArea(){
		areaService.saveArea(model);
		return SUCCESS;
	}
	//获取所有区域
	@Action(value="allarea", results={@Result(name="success",type="json")})
	public String getAllArea(){
		List<Area> list = areaService.getAllArea();
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
	
	
	//分页查询区域
	@Action(value="allareabypage", results={@Result(name="success",type="json")})
	public String allArea(){
		//封装分页数据
		Pageable pageable = new PageRequest(page-1,rows);
		//封装查询条件
		/*Specification<Area> specification = new Specification<Area>() {
			List<Predicate> list = new ArrayList<Predicate>();
			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				if (StringUtils.isNotBlank(model.getProvince())) {
					Predicate predicate1 = cb.like(root.get("province").as(String.class),"%"+model.getProvince()+"%");
					list.add(predicate1);
				}
				if (StringUtils.isNotBlank(model.getCity())) {
					Predicate predicate2 = cb.like(root.get("city").as(String.class),"%"+model.getCity()+"%");
					list.add(predicate2);
				}
				if (StringUtils.isNotBlank(model.getDistrict())) {
					Predicate predicate3 = cb.like(root.get("district").as(String.class),"%"+model.getDistrict()+"%");
					list.add(predicate3);
				}
				System.out.println(cb.and(list.toArray(new Predicate[0])));
				return cb.and(list.toArray(new Predicate[0]));
			}
		};*/
		Specification<Area> specification = getSpecification(model);
		//查找所有符合条件的记录
		Page<Area> page = areaService.findAllByPage(pageable,specification);
		//将结果压入值栈
		pushPageDataToValueStack(page);
		return SUCCESS;
	}
	
	//接收上传文件
	private File file;
	private String fileFileName;
	public void setFile(File file) {
		this.file = file;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	//从文件批量插入区域
	@Action(value="addareas", results={@Result(name="success",location="../pages/base/area.html",type="redirect")})
	public String addAreas(){
		List<Area> areas = new ArrayList<Area>();
		if (fileFileName.endsWith(".xls")) {
			try {
				HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
				HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
				for (Row row : sheet) {
					Area area = new Area();
					if (row.getRowNum()==0) {
						continue;
					}
					if (row.getCell(0)==null ||StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
						continue;
					}
					area.setId(row.getCell(0).getStringCellValue());
					area.setProvince(row.getCell(1).getStringCellValue());
					area.setCity(row.getCell(2).getStringCellValue());
					area.setDistrict(row.getCell(3).getStringCellValue());
					area.setPostcode(row.getCell(4).getStringCellValue());
					String pstr = area.getProvince().substring(0, area.getProvince().length()-1);
					String cstr = area.getCity().substring(0, area.getCity().length()-1);
					String dstr = area.getDistrict().substring(0,area.getDistrict().length()-1);
					String[] strs = pinyin4jUtils.getHeadByString(pstr+cstr+dstr);
					StringBuffer scode = new StringBuffer();
					for (String string : strs) {
						scode.append(string);
					}
					area.setShortcode(scode.toString());
					area.setCitycode(pinyin4jUtils.hanziToPinyin(cstr));
					areas.add(area);
				}
				areaService.saveAreas(areas);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return SUCCESS;
	}

	//导出区域数据
	@Action(value="downfile")
	public void downloadArea(){
		List<Area> list = areaService.findAllArea();
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("区域信息");
		HSSFRow row = sheet.createRow(0);
		row.createCell(0).setCellValue("编码");
		row.createCell(1).setCellValue("省");
		row.createCell(2).setCellValue("市");
		row.createCell(3).setCellValue("城市编码");
		row.createCell(4).setCellValue("区");
		row.createCell(5).setCellValue("邮编");
		row.createCell(6).setCellValue("简码");
		
		for (int i = 0; i < list.size(); i++) {
			HSSFRow rowtem = sheet.createRow(i+1);
			rowtem.createCell(0).setCellValue(list.get(i).getId());
			rowtem.createCell(1).setCellValue(list.get(i).getProvince());
			rowtem.createCell(2).setCellValue(list.get(i).getCity());
			rowtem.createCell(3).setCellValue(list.get(i).getCitycode());
			rowtem.createCell(4).setCellValue(list.get(i).getDistrict());
			rowtem.createCell(5).setCellValue(list.get(i).getPostcode());
			rowtem.createCell(6).setCellValue(list.get(i).getShortcode());
		}
		//定义文件名称
		String fileName = "aaaa.xls";
		//设置头信息
		HttpServletResponse response = ServletActionContext.getResponse();
		//disponsition浏览器以附件形式打开
		response.setHeader("content-disposition", "attachment;filename="+fileName);
		//设置文件格式
		String mimeType = ServletActionContext.getServletContext().getMimeType(fileName);
		response.setContentType(mimeType);
		//将输出流对接
		try {
			workbook.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
